package com.fatcat.easybuy.listener;

import com.fatcat.easybuy.pojo.EasyBuyOrder;
import com.fatcat.easybuy.service.EasyBuyOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;


public class OrderExpireListener extends KeyExpirationEventMessageListener {

    @Autowired
    private EasyBuyOrderService easyBuyOrderService;

    private static final String ORDER_EXPIRE_KEY_PREFIX = "order:";
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderExpireListener.class);

    /**
     * 必须传入Redis消息容器（父类要求），并注入业务Service
     */
    public OrderExpireListener(RedisMessageListenerContainer container) {
        super(container); // 调用父类构造，关联监听容器
    }

    /**
     * Redis键过期时触发
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取过期的Redis键
        String expiredRedisKey = message.toString();
        LOGGER.info("Redis键过期事件触发，键：{}", expiredRedisKey);
        // 处理 "order:" 前缀的键
        if (expiredRedisKey.startsWith(ORDER_EXPIRE_KEY_PREFIX)) {
            //解析出订单ID
            String orderId = expiredRedisKey.replace(ORDER_EXPIRE_KEY_PREFIX, "");

            try {
                EasyBuyOrder order = easyBuyOrderService.getOrderById(Long.parseLong(orderId));
                // 取消超时未支付的订单
                boolean cancelSuccess = easyBuyOrderService.closeOrder(order.getSerialNumber());
                if (cancelSuccess) {
                    LOGGER.info("订单[{}]因超时未支付，已自动取消", orderId);
                } else {
                    LOGGER.error("订单[{}]状态异常，取消失败（可能已支付/已取消）", orderId);
                }
            } catch (NumberFormatException e) {
                LOGGER.error("订单ID解析失败，键：{}，错误：{}", expiredRedisKey, e.getMessage());
            } catch (Exception e) {
                LOGGER.error("取消订单[{}]失败，错误：{}", orderId, e.getMessage());
            }
        }
    }


}